/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Microsoft
 * Date: 2023-03-30
 * Time: 20:58
 */
public class HashBuck {
    static class Node {
        public int key;
        public int val;
        public Node next;

        public Node(int key,int val) {
            this.key = key;
            this.val = val;
        }
    }

    public Node[] array;
    public int usedSize;
    //负载因子
    public static final double LOAD_FACTOR = 0.75;

    public HashBuck(){
        array = new Node[10];
    }

    public void put(int key,int val){
        int index = key % array.length;
        Node cur = array[index];
        //无论头插尾插都需要遍历判断是否已经存在，如果存在就进行覆盖
        while (cur != null) {
            if (cur.key == key) {
                cur.val = val;
                return;
            }
            cur = cur.next;
        }
        //采用头插法进行插入
        Node node = new Node(key,val);
        node.next = array[index];
        array[index] = node;
        usedSize++;
        if (calculateLoadFactor() >= LOAD_FACTOR) {
            //扩容
            resize();
        }
    }

    private void resize() {
        Node[] newArray = new Node[2* array.length];
        //一定要记住，每个元素都要进行重新的哈希计算
        for (int i = 0; i < array.length; i++) {
            Node cur = array[i];
            while (cur != null) {
                Node curNext = cur.next;
                int index = cur.key % newArray.length;//找到了在新的数组当中的位置
                cur.next = newArray[index];
                newArray[index] = cur;
                cur = curNext;
            }
        }

        array = newArray;
    }

    //计算负载银子
    private double calculateLoadFactor(){
        return usedSize*1.0 / array.length;
    }

    //根据key获取所对应的value值
    public int get(int key) {
        int index = key % array.length;
        Node cur = array[index];
        while (cur != null) {
            if (cur.key == key) {
                return cur.val;
            }
            cur = cur.next;
        }
        return -1;
    }
}
